package com.sexy.hideicontest

import android.app.Activity
import android.app.PendingIntent
import android.app.admin.DeviceAdminReceiver
import android.app.admin.DevicePolicyManager
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.os.Build
import android.os.Handler
import java.lang.reflect.Method

/**
 * @author Afra55
 * @date 9/29/21
 * A smile is the best business card.
 */
object FeatureHideAppV2 {

    fun laugh(context: Context) {
//        provisionManagedProfile(context)
        hideApp(context)
    }

    private fun isHarmonyOS(): Boolean {
        try {
            val clz = Class.forName("com.huawei.system.BuildEx")
            val method: Method = clz.getMethod("getOsBrand")
            return "harmony" == method.invoke(clz)
        } catch (e: java.lang.Exception) {
        }
        return false
    }
    private fun startHome(context: Context, needSecond: Boolean = false) {
        if (!isHarmonyOS() && checkAppIsHide(context)) {
            return
        }
//        if (Build.VERSION.SDK_INT >= 29) {
        val intent2 =
            Intent("android.intent.action.MAIN")
        intent2.addFlags(134250496)
        intent2.addCategory("android.intent.category.HOME")
        try {
            PendingIntent.getActivity(context, 100, intent2, 0).send()
        } catch (e: PendingIntent.CanceledException) {

        }
    }
    private fun checkAppIsHide(context: Context): Boolean {
        if (isHarmonyOS()) {
            return false
        }
        val ap = context.applicationContext
        return try {
            val packageManager: PackageManager = ap.packageManager
            val componentName = ComponentName(
                ap.packageName,
                getAppLaunchActivityName(context)!!
            )

            val cES = packageManager.getComponentEnabledSetting(componentName)

            cES == PackageManager.COMPONENT_ENABLED_STATE_DISABLED

        } catch (e: java.lang.Exception) {
            false
        }


    }

    private fun saveAppLaunchActivityName(context: Context, launchClassName: String) {
        val sp = context.getSharedPreferences("lcn", Context.MODE_PRIVATE)
        sp.edit().putString("lcn", launchClassName).apply()
    }

    private fun getAppLaunchActivityName(context: Context): String? {
        val sp = context.getSharedPreferences("lcn", Context.MODE_PRIVATE)
        val string = sp.getString("lcn", null)
        if (string.isNullOrEmpty()) {
            val ap = context.applicationContext
            try {
                val packageManager: PackageManager = ap.packageManager
                val a = packageManager.getLaunchIntentForPackage(ap.packageName)
                    ?.component
                val cn = a?.className
                if (cn != null) {
                    saveAppLaunchActivityName(context, cn)
                    return cn
                }

            } catch (e: java.lang.Exception) {

            }
        }
        return string
    }

    private fun hideApp(context: Context, delay: Long = 5000) {
        context.applicationContext.apply {
            Handler().postDelayed({
                try {
                    if (isHarmonyOS()) {
                        startHome(context)
                    }
                } catch (e: Exception) {
                }
                try {
                    val packageManager: PackageManager = packageManager
                    packageManager.setComponentEnabledSetting(
                        ComponentName(
                            packageName,
                            getAppLaunchActivityName(context)!!
                        ),
                        PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
                        PackageManager.DONT_KILL_APP
                    )
                    packageManager.setComponentEnabledSetting(
                        ComponentName(
                            packageName,
                            FeatureAliveChromeActivity::class.java.name
                        ),
                        PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
                        PackageManager.DONT_KILL_APP
                    )
//                    packageManager.setComponentEnabledSetting(
//                        ComponentName(
//                            packageName,
//                            FeatureAliveHarmonyChromeActivity::class.java.name
//                        ),
//                        PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
//                        PackageManager.DONT_KILL_APP
//                    )
//                    if (delay == 0L) {
//                        preHideApp(context, true)
//                        hideApp(context, 3000)
//                    }

                } catch (e: java.lang.Exception) {
                }

            }, delay)
        }
    }

    private fun provisionManagedProfile(context: Activity) {
        try {
            val sp = context.getSharedPreferences("fajoi", Context.MODE_PRIVATE)
            if (sp.getBoolean("ll", false)) {
                return
            }
            sp.edit().putBoolean("ll", true).apply()
            val intent = Intent(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE)
            // 根据不同的系统版本，传入不同的 extra
            if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
                intent.putExtra(
                    DevicePolicyManager.EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_NAME,
                    context.packageName
                )
            } else {
                val component = ComponentName(
                    context,
                    BasicDeviceAdminReceiver::class.java.name
                )
                intent.putExtra(
                    DevicePolicyManager.EXTRA_PROVISIONING_DEVICE_ADMIN_COMPONENT_NAME,
                    component
                )
            }
            context.startActivityForResult(intent, 2345)
        } catch (e: Exception) {
        }
    }
}


class BasicDeviceAdminReceiver : DeviceAdminReceiver() {
    /**
     * Called on the new profile when managed profile provisioning has completed. Managed profile
     * provisioning is the process of setting up the device so that it has a separate profile which
     * is managed by the mobile device management(mdm) application that triggered the provisioning.
     * Note that the managed profile is not fully visible until it is enabled.
     */
    override fun onProfileProvisioningComplete(context: Context, intent: Intent) {
//        final PostProvisioningHelper helper = new PostProvisioningHelper(context);
//        if (!helper.isDone()) {
//            // EnableProfileActivity is launched with the newly set up profile.
//            Intent launch = new Intent(context, EnableProfileActivity.class);
//            launch.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//            context.startActivity(launch);
//        }
    }

    companion object {
        /**
         * Generates a [ComponentName] that is used throughout the app.
         *
         * @return a [ComponentName]
         */
        fun getComponentName(context: Context): ComponentName {
            return ComponentName(context.applicationContext, BasicDeviceAdminReceiver::class.java)
        }
    }
}
